package com.sqfw.project.knowledge.service.impl;

import com.alibaba.fastjson2.JSONObject;
import com.sqfw.framework.web.domain.AjaxResult;
import com.sqfw.project.knowledge.service.ElderlyAllowanceService;
import com.sqfw.project.utils.HttpClientUtils;
import lombok.extern.slf4j.Slf4j;
import org.apache.commons.lang3.StringUtils;
import org.springframework.beans.factory.annotation.Value;
import org.springframework.stereotype.Service;
import sun.misc.BASE64Encoder;


import javax.crypto.Cipher;
import javax.crypto.spec.SecretKeySpec;
import java.util.HashMap;
import java.util.*;

/**
 * 养老津贴
 *
 * @author tangxt
 * @date 2024-06-20
 * */
@Slf4j
@Service
public class ElderlyAllowanceServiceImpl implements ElderlyAllowanceService {

    /** 查询 养老津贴 apiUrl (一网通办-服务中台)*/
    @Value("${elderlyAllowance.apiUrl}")
    private  String apiUrl;

    /** 查询 养老津贴 appid  (一网通办-服务中台)*/
    @Value("${elderlyAllowance.appid}")
    private  String appid;

    /** 查询 养老津贴 appid  (一网通办-服务中台)*/
    @Value("${elderlyAllowance.appkey}")
    private  String appkey;

    /** 查询 养老津贴 appid  (一网通办-服务中台)*/
    @Value("${elderlyAllowance.apiname}")
    private  String apiname;

    /** 请求中台的地址：/clientgateway/ */
    private static final String ELDERLY_ALLOWANCE_URL = "/clientgateway/";

    private static final String HTTP_CODE_200 = "200";

    /**
     * 查询养老津贴数据
     * @param cetf 身份证号
     * @return
     * */
    @Override
    public AjaxResult queryElderlyAllowance(String cetf) {
        try {
            String elderlyAllowanceUrl = apiUrl + ELDERLY_ALLOWANCE_URL;
            log.info("查询养老津贴数据-地址url: {}", elderlyAllowanceUrl);
            String signature = this.getSignature();
            if (StringUtils.isBlank(signature)) {
                return AjaxResult.error("生成签名失败！");
            }
            Map<String, String> headerParam = new HashMap<>();
            headerParam.put("appid", appid);
            headerParam.put("apiname", apiname);
            headerParam.put("signature", signature);
            log.info("请求头-headerParam: {}", headerParam.toString());
            Map<String, String> params = new HashMap<>();
            params.put("cetf", cetf);
            log.info("查询参数-params: {}", params.toString());
            String ajaxResult = HttpClientUtils.postJson(elderlyAllowanceUrl, headerParam, params);
            log.info("查询养老津贴返回-ajaxResult: {}", ajaxResult);
            if (StringUtils.isBlank(ajaxResult)) {
                log.info("查询-养老津贴-调用接口失败");
                return AjaxResult.error("查询-养老津贴-调用接口失败");
            }else {
                JSONObject resJson = JSONObject.parseObject(ajaxResult);
                // 成功
                if (HTTP_CODE_200.equals(resJson.getString("status"))) {
                    JSONObject jsonObject = resJson.getJSONObject("data");
                    return AjaxResult.success(jsonObject);
                }else {
                    log.error("查询-养老津贴-失败-status：{}, message: {}",
                            resJson.getString("status"), resJson.getString("message"));
                    return AjaxResult.error(resJson.getString("message"));
                }
            }
        }catch (Exception e) {
            e.printStackTrace();
            return AjaxResult.error("接口异常");
        }

    }


    private String getSignature() {
        try {
            String key = appkey.replace("-", "");
            long timestamp = System.currentTimeMillis() / 1000;
            String stringtosign = appid + apiname + timestamp;
            SecretKeySpec keySpec = new SecretKeySpec(key.getBytes("utf-8"), "AES");
            Cipher cipher = Cipher.getInstance("AES/ECB/PKCS5Padding");
            cipher.init(Cipher.ENCRYPT_MODE, keySpec);
            // stringtosign是1.1生成的签名字符串
            byte[ ] bytes = cipher.doFinal(stringtosign.getBytes("utf-8"));
            // sun.misc.BASE64Encoder 有换行的bug
//            String signature = new BASE64Encoder().encode(bytes);
            return Base64.getEncoder().encodeToString(bytes);
        }catch (Exception e) {
            e.printStackTrace();
            return null;
        }
    }



}
